<template>
	<view class="p-30">
		<view class="bg-fff br-10  m-b-30">
			<person-detail :infoList="infoList" :info="info"></person-detail>
		</view>
		<view class="bg-fff br-10 p-20 m-b-30">
			<image @click="addEquip" src="@/static/add-equipment.png" style="width: 100%;height: 150rpx;">
			</image>
			<view class="table-label">申报仪器一览</view>
			<u-row customStyle="padding: 20rpx;color: #999999;background: #f1f1f1;font-size: 22rpx;">
				<u-col span="7">
					器具名称
				</u-col>
				<u-col span="4">
					准确度
				</u-col>
				<u-col span="1">
					操作
				</u-col>
			</u-row>
			<u-empty v-if="!equipList.length" marginTop="30rpx" mode="list" icon="/static/null.png">
			</u-empty>
			<u-row v-else customStyle="padding: 20rpx;color: #333;border-bottom: 1px solid #E7E8EC;font-size: 22rpx;"
				v-for="(item, index) in equipList" :key="item.id">
				<u-col span="7">
					<view>{{ item.name }}({{ item.modelNumber }})</view>
				</u-col>
				<u-col span="4">
					<view>
						{{ item.devicePrecision }}
					</view>
				</u-col>
				<u-col span="1">
					<text class="del-btn" @click="delEquip(index)">删除</text>
				</u-col>
			</u-row>
			<u-radio-group v-model="formData.status" placement="row" shape="shape">
				<u-radio :customStyle="{ margin: '6px 20px 6px 0' }" v-for="(item, index) in typeList" :key="index"
					:label="item.name" :name="item.name" @change="radioChange">
				</u-radio>
			</u-radio-group>
		</view>
		<view class="bg-fff br-10 p-x-30 m-b-30">
			<u--form labelPosition="top" :model="formData" :rules="rules" ref="uForm" labelWidth="80">
				<u-form-item label="故障原因" prop="description" :required="true">
					<u--textarea v-model="formData.description" height="80" :maxlength="-1" :show-confirm-bar="false"
						:confirmType="null" placeholder="请输入内容"></u--textarea>
				</u-form-item>
				<!-- @afterRead="afterRead" :previewFullImage="true" :required="true" -->
				<u-form-item label="图片上传" prop="fileList">
					<u-upload ref="uUpload" @afterRead="afterRead" :auto-upload="false" :file-list="formData.fileList" name="img"
						multiple :maxCount="10" @delete="deletePic">
					</u-upload>
				</u-form-item>
			</u--form>
		</view>
		<u-button type="primary" text="提交申请" @click="onSubmit"></u-button>
		<u-modal :show="modalShow" :content="content" :showCancelButton="true" @cancel="modalShow=false;"
			@confirm="onDeleteConfirm"></u-modal>
	</view>
</template>

<script>
	import {
		uploadbaseUrl
	} from '@/request/request.js'
	export default {
		data() {
			return {
				formData: {
					status: '',
					description: '',
					instrumentsId: '',
					creatName: '',
					phone: '',
					declareDate: '',
					fileList: []
				},
				info: {
					realName: '',
					mobile: '',
					date: '',
				},
				equipList: [],
				infoList: [{
						name: '申报人',
						key: 'realName'
					},
					{
						name: '联系方式',
						key: 'mobile'
					},
					{
						name: '申报日期',
						key: 'date'
					},
				],
				typeList: [{
						name: '可正常使用'
					},
					{
						name: '无法使用'
					},
					{
						name: '返厂维修'
					},
				],
				rules: {
					'description': {
						type: 'string',
						required: true,
						message: '请填写故障原因',
						trigger: ['blur', 'change']
					},
					'fileList': {
						type: 'array',
						required: true,
						message: '请上传图片',
						trigger: ['blur', 'change']
					},
				},
				id: '',
				taskId: '',
				backComment: '',
				deleteEvent: {},
				modalShow: false,
				content: '确认要删除该图片？删除后将无法恢复！',
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
		// 监听自定义事件并进行页面刷新操作
		onShow() {
			uni.$on('refresh', (data) => {
				if (data.refresh) {
					// 刷新操作
					this.getdefautdata()
				}
			});
		},
		onUnload() {
			uni.$off('refresh'); // 需要手动解绑自定义事件
		},
		onLoad(option) {
			this.id = option.id || ''
			this.taskId = option.taskId || ''
			this.getdefautdata(option.id)
		},

		onPullDownRefresh() {
			this.info.date = new Date().Format('yyyy-MM-dd hh:mm:ss')
			uni.stopPullDownRefresh()
		},
		methods: {
			// 判断取默认值还是详情
			getdefautdata(id) {
				if (id) {
					this.getDetail()
					return
				} else {
					this.getSelectAll()
					this.getUserInfo()
				}
			},
			radioChange() {

			},
			// 获取选择的仪器
			getSelectAll() {
				try {
					const list = uni.getStorageSync('selectAll');
					if (list) {
						this.equipList = JSON.parse(list)
						console.log(this.equipList)
						this.formData.instrumentsId = this.equipList[0].id //用于提交
					}
				} catch (e) {
					// this.equipList = []
				}
			},
			// 详情
			getDetail() {
				this.$api.gettroubleDetail({
					id: this.id
				}).then(res => {
					// 必须要用这个Object.assign ，防止图片再次上传删除能有指向
					this.formData = Object.assign(this.formData, res.data)
					this.formData.status = this.filterdetail(res.data.status)
					this.formData.description = res.data.description.replaceAll("/r/n", "<br>")
					this.info = res.data
					if (this.info) {
						this.info.realName = res.data.creatName
						this.info.mobile = res.data.phone
						this.info.date = res.data.declareDate
					}
					this.equipList = [res.data.instrumentsDTO]
					let files = JSON.parse(JSON.stringify(res.data.troubleFiles))
					let arr = []
					if (res.data.troubleFiles && res.data.troubleFiles.length > 0) {
						this.formData.fileList = files.map((item) => {
							item.url = `${uploadbaseUrl}/${item.uploadName}`
							return item
						})
					}
				})
			},
			getUserInfo() {
				const info = uni.getStorageSync('userInfo');
				if (info) {
					this.info = JSON.parse(info)
					this.info.date = new Date().Format('yyyy-MM-dd hh:mm:ss')
				}
			},
			// 添加设备
			addEquip() {
				uni.setStorageSync('loanInfo', JSON.stringify({
					externalName: this.info.externalName,
					externalPhone: this.info.externalPhone
				}))
				uni.navigateTo({
					url: `/pages/selectEquipment/selectEquipment?from=form`
				});
			},
			// 删除仪器
			delEquip(index) {
				this.equipList.splice(index, 1)
				this.formData.instrumentsId = ""
			},
			// 过滤数据转化
			filterFunction(value) {
				let resolveData
				switch (value) {
					case '可正常使用':
						resolveData = 1;
						break;
					case '无法使用':
						resolveData = 2;
						break;
					case '返厂维修':
						resolveData = 3;
						break;
					default:
						resolveData = 0;
				};
				return resolveData
			},
			// 反过滤数据转化 数字转名称
			filterdetail(value) {
				let resolveData
				switch (value) {
					case 1:
						resolveData = '可正常使用';
						break;
					case 2:
						resolveData = '无法使用';
						break;
					case 3:
						resolveData = '返厂维修';
						break;
					default:
						resolveData = '';
				};
				return resolveData
			},
			// 图片上传后端
			uploadFilePromise(id, type) {
				const token = uni.getStorageSync('token') || "";
				let files = []
				this.formData.fileList.map((item) => {
					files.push({
						name: 'files',
						uri: item.url,
						file: item
					})
				})
				console.log(files)
				let params = {
					'relatedId': id,
					'rt': 'trouble',
				}
				let that = this
				let resarr = []
				// return
				//res 是本地图片images遍历上传以后返回的promise对象的集合
				files.map(item => {
					// 新加的图片上传
					if (!item.file.fileId) {
						let res = this.$api.addupload(params, item.file)
						resarr.push(res)
					}
				})
				//最后调用Promise.all
				Promise.all(resarr).then(res => {
					console.log('全部成功')
					if (type == 'edit') {
						this.backComment = true
						that.openFlow(id)
					} else {
						this.backComment = false
						that.openFlow(id)
					}
					//所有图片上传成功时所需执行代码块
					//比如可以将upload函数中success 回调里压栈的数据发送给后台
				}).catch(e => {
					console.log('上传的部分图片有误，请重新上传')
					if (type == 'edit') {
						this.backComment = true
						that.openFlow(id)
					} else {
						this.backComment = false
						that.openFlow(id)
					}
				})
			},
			// 开启工作流、重新提交
			openFlow(id) {
				let params = {
					processDefinitionKey: "trouble",
					businessKey: id,
					variables: {
						userId: this.info.id,
						trouble: {
							instrumentsId: this.formData.instrumentsId,
							status: Number(this.filterFunction(this.formData.status)),
							description: this.formData.description
						}
					},
				}
				let apiName = 'openFlow'
				if (this.backComment) {
					apiName = 'completeByVariables'
					params = {  
						taskId: this.taskId,
						processDefinitionKey: "trouble",
						businessKey: id,
						params: { //修改后走的流程key不同 注意
							userId: this.info.id,
							trouble: {
								instrumentsId: this.formData.instrumentsId,
								status: Number(this.filterFunction(this.formData.status)),
								description: this.formData.description
							}
						},
					}
				}
				this.$api[apiName](params).then(res => {
					uni.showToast({
						title: '提交成功',
						icon: 'none'
					})
					// 跳转回上一页
					uni.navigateBack({
						delta: 1
					});
				})
			},
			// 提交数据
			async onSubmit() {
				if (this.equipList.length == 0) {
					uni.$u.toast('请选择设备')
					return
				}
				if (this.formData.status == '') {
					uni.$u.toast('请选择故障类型')
					return
				}
				let params = {
					status: this.filterFunction(this.formData.status),
					description: this.formData.description,
					declareDate: this.info.date,
					instrumentsId: this.formData.instrumentsId,
				}
				this.$refs.uForm.validate().then(res => {
					uni.setStorageSync('selectAll', JSON.stringify([]))
					if (this.id) {
						params.id = this.id
						// 修改
						this.$api.editMalfunction(params).then(res => {
							if (res.msg == 'success') {
								this.uploadFilePromise(this.id, 'edit')
							}
						})
					} else {
						// 新增
						this.$api.addMalfunction(params).then(res => {
							if (res.msg == 'success') {
								if (res.data.id) {
									this.uploadFilePromise(res.data.id, 'add')
								}
							}
						})
					}

				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},

			// 删除图片
			deletePic(event) {
				this.modalShow = true
				this.deleteEvent = event
			},
			// 删除图片 如果是服务器端的图片择调用删除接口
			async onDeleteConfirm() {
				if (this.deleteEvent.file.fileId) {
					await this.$api.deletupload([this.deleteEvent.file.fileId])
				}
				this.formData.fileList.splice(this.deleteEvent.index, 1)
				this.modalShow = false
			},
			// 新增图片
			async afterRead(event) {
				// console.log(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.formData.fileList.length
				lists.map((item) => {
					this.formData.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					console.log(lists)
					// const result = await this.uploadFilePromise(lists[i].url)
					let item = this.formData.fileList[fileListLen]
					this.formData.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						// url: result
					}))
					fileListLen++
				}
			},

		}
	}
</script>

<style lang="scss" scoped>
	.table-label {
		font-size: 25rpx;
		color: #666666;
		padding: 20rpx 0;
	}

	.del-btn {
		font-size: 22rpx;
		text-decoration: underline;
		color: #D91A1A;
		cursor: pointer;
	}


	::v-deep .u-form-item__body__left__content__label {
		font-size: 25rpx !important;
	}
</style>